<script setup lang="ts">
import API from '@/services';
import { Message } from '@arco-design/web-vue';
import { onMounted, reactive, ref, useAttrs, watch } from 'vue';
import LeftJoinForm from '../../../components/LeftJoinForm/index.vue';

const props = defineProps<{ id: number | string }>();
const attrs = useAttrs();
const emit = defineEmits(['success']);
const defaultFormData = {
  list: [
    {
      value: {
        tableId: undefined,
        joinTableId: undefined,
        tableField: undefined,
        joinTableField: undefined
      } as any
    }
  ]
};
interface OptionsI {
  label: string;
  value: string | number | undefined;
  tableName: string;
}
const tableD = ref<any>();
const fetchModelRelation = async () => {
  try {
    const { data } = await API.dataModel.getGetModelRelationByModelIdById({
      id: props.id as number
    });
    formData.list =
      data?.map((d) => {
        return {
          value: {
            ...d
          }
        };
      }) || defaultFormData.list;
    // tableOptions = 第一条数据的 事实表(这里面隐藏的逻辑就是第一条是 事实表) + 维表
    tableD.value = data?.[0] || null;
  } catch {}
};
onMounted(() => {
  fetchModelRelation();
  getDimTableData();
});
const formData = reactive(defaultFormData);
const tableLeftOptions = ref<any[]>([]);
const dimTableOptions = ref<OptionsI[]>([]);
const getDimTableData = async () => {
  try {
    const res = await API.dataTable.postDataTableGetTableList({ tableType: 2 });
    dimTableOptions.value =
      res?.data?.map((d) => {
        return {
          label: `${d.tableName}`,
          tableName: d.tableName || '',
          value: d.id
        };
      }) || [];
  } catch (error) {}
};
const onAddList = () => {
  formData.list.push({
    value: {
      tableId: undefined,
      joinTableId: undefined,
      tableField: undefined,
      joinTableField: undefined
    }
  });
};
const onRemoveList = (index: number) => {
  formData.list.splice(index, 1);
};
watch([tableD, dimTableOptions], () => {
  if (tableD.value) {
    tableLeftOptions.value = [
      {
        label: `${tableD.value.tableName}`,
        tableName: tableD.value.tableName || '',
        value: tableD.value.tableId
      }
    ].concat(dimTableOptions.value);
  }
});
const getTableOption = (options: any[], value: string | number | undefined) => {
  if (!value) {
    return {};
  }
  const item = options.find((option) => option.value === value) || {};
  return item;
};
const formRef = ref();
const onBeforeOkAsync = async () => {
  const err = await formRef.value.validate();
  if (!err) {
    try {
      const list = formData.list.map((val) => {
        const tableData = getTableOption(
          tableLeftOptions.value,
          val.value.tableId
        );
        const joinTableData = getTableOption(
          dimTableOptions.value,
          val.value.joinTableId
        );
        return {
          ...val.value,
          tableName: tableData.tableName,
          joinTableName: joinTableData.tableName
        };
      });
      const { code } = await API.dataModel.postUpdateModelRelation({
        id: props.id as number,
        // @ts-ignore
        list
      });
      if (code !== 200) {
        throw new Error('错误');
      }
      return true;
    } catch (error) {
      throw error;
    }
  }
  {
    throw new Error('校验错误');
  }
};
const onBeforeOk = (done: any) => {
  onBeforeOkAsync()
    .then(() => {
      Message.success('更新模型成功');
      emit('success');
      done(true);
    })
    .catch((e) => {
      done(false);
    });
};
const onDrawerClose = () => {
  fetchModelRelation();
};
</script>
<template>
  <a-drawer
    unmountOnClose
    :width="684"
    @before-ok="onBeforeOk"
    @close="onDrawerClose"
    v-bind="attrs"
  >
    <template #title
      ><span style="font-weight: bold">修改事实表关联情况</span></template
    >
    <a-form ref="formRef" :model="formData" auto-label-width>
      <a-form-item show-colon required label="事实表关联">
        <a-tooltip content="必须为事实表关联维表，也可追加维表与维表的关联。">
          <icon-info-circle :strokeWidth="1" />
        </a-tooltip>
      </a-form-item>
      <div>
        <LeftJoinForm
          v-for="(post, index) of formData.list"
          v-model="post.value"
          :key="index"
          :disable-remove="index === 0"
          :tableDisabled="index === 0"
          :fieldPath="`list.${index}.value`"
          :tableLeftOptions="tableLeftOptions"
          :table-right-options="dimTableOptions"
          @remove="() => onRemoveList(index)"
        />
      </div>
      <a-button @click="onAddList" type="outline" style="width: 80px"
        >+添加</a-button
      >
    </a-form>
  </a-drawer>
</template>
